<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\webautocode\extend\service;

use think\Db;
use think\db\Query;

/**
 * 基础数据服务
 * Class DatasService
 * @package service
 * @author Anyon <zoujingli@qq.com>
 * @date 2017/03/22 15:32
 */
class DatasService
{

    /**
     * 删除指定序号
     * @param string $sequence
     * @param string $type
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function deleteSequence($sequence, $type = 'SYSTEM')
    {
        $data = ['sequence' => $sequence, 'type' => strtoupper($type)];
        return Db::name('SystemSequence')->where($data)->delete();
    }

    /**
     * 生成唯一序号 (失败返回 NULL )
     * @param int $length 序号长度
     * @param string $type 序号顾类型
     * @return string
     */
    public static function createSequence($length = 10, $type = 'SYSTEM')
    {
        $times = 0;
        while ($times++ < 10) {
            list($i, $sequence) = [0, ''];
            while ($i++ < $length) {
                $sequence .= ($i <= 1 ? rand(1, 9) : rand(0, 9));
            }
            $data = ['sequence' => $sequence, 'type' => strtoupper($type)];
            if (Db::name('SystemSequence')->where($data)->count() < 1 && Db::name('SystemSequence')->insert($data) !== false) {
                return $sequence;
            }
        }
        return null;
    }

    /**
     * 数据增量保存
     * @param Query|string $dbQuery 数据查询对象
     * @param array $data 需要保存或更新的数据
     * @param string $key 条件主键限制
     * @param array $where 其它的where条件
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function save($dbQuery, $data, $key = 'id', $where = [])
    {
        $db = is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery;
        $where[] = [$key, 'eq', isset($data[$key]) ? $data[$key] : ''];
        if (Db::name($db->getTable())->where($where)->count() > 0) {
            return Db::name($db->getTable())->strict(false)->where($where)->update($data) !== false;
        }
        return Db::name($db->getTable())->strict(false)->insert($data) !== false;
    }

    /**
     * desc：
     * author：wh
     * @param $dbQuery
     * @param $data
     * @param string $key
     * @param array $where
     * @return bool
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function toSave($dbQuery, $data, $key = 'id', $where = [], $config = [])
    {
        $db = is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery;
        $where[] = [$key, 'eq', isset($data[$key]) ? $data[$key] : ''];
        if (Db::name($db->getTable())->where($where)->count() > 0) {
            $db_obj = Db::name($db->getTable());
            $update_result = $db_obj->strict(false)->where($where)->update($data) !== false;
            $title = isset($data['title'])?$data['title']:'更新模型配置';
            self::auto_sync_sql($db_obj->getLastSql().';', $title, $config);
            return $update_result;
        }
        $db_obj = Db::name($db->getTable());
        $insert_result = $db_obj->strict(false)->insertGetId($data);
        $title = isset($data['title'])?$data['title']:'新增模型配置';
        self::auto_sync_sql($db_obj->getLastSql().';', $title, $config);
        return $insert_result;
    }

    /**
     * 更新数据表内容
     * @param Query|string $dbQuery 数据查询对象
     * @param array $where 额外查询条件
     * @return bool|null
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function update(&$dbQuery, $where = [], $config=[])
    {
        $request = app('request');
        $db = is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery;
        list($pk, $table) = [$db->getPk(), $db->getTable()];
        list($field, $value) = [$request->post('field', ''), $request->post('value', '')];
        $where[] = [empty($pk) ? 'id' : $pk, 'in', explode(',', $request->post('id', ''))];
        // 删除模式，如果存在 is_deleted 字段使用软删除
        if ($field === 'delete') {
            if (method_exists($db, 'getTableFields') && in_array('is_deleted', $db->getTableFields())) {
                $db_obj = Db::name($db->getTable());
                $update_result = $db_obj->where($where)->update(['is_deleted' => '1']) !== false;
                self::auto_sync_sql($db_obj->getLastSql().';', '软删除模型配置', $config);
                return $update_result;
            }
            $db_obj = Db::name($db->getTable());
            $update_result = $db_obj->where($where)->delete() !== false;
            self::auto_sync_sql($db_obj->getLastSql().';', '删除模型配置', $config);
            return $update_result;
        }
        // 更新模式，更新指定字段内容
        $db_obj = Db::name($db->getTable());
        $update_result = $db_obj->where($where)->update([$field => $value]) !== false;
        self::auto_sync_sql($db_obj->getLastSql().';', '软删除指定模型配置', $config);
        return $update_result;
    }
    /**
     * [同步sql到.sql文件]
     *
     * @param $sql
     * @param string $title
     * @example
     * @see
     * @link
     */
    static function auto_sync_sql($sql, $title = '', $config=[]){
        if(empty($config)) return false;//直接结束
        if(!config('app.app_debug')) return false;//非调试模式直接结束

        $__file__ = empty($config['file'])?:$config['file'];
        $__line__ = empty($config['line'])?:$config['line'];

        //目录前缀
        $dir =  config('app.ROOT_PATH_PRO').'/sql/';
        if(!file_exists($dir)){
            mkdir($dir, 0777, true);
        }
        //sql文件存储名称
        if(empty($config['sql_file'])){
            $sql_file = 'sql-sync-auto';
        }else{
            $sql_file = $config['sql_file'];
        }
        $dir .= $sql_file;//添加版本号
        $dir .= '.sql';//后缀
        $title = "\r\n".'-- '.date('Ymd H:i:s').' '.$title.' '.$__file__.' '.$__line__."\r\n";//说明

        file_put_contents($dir, $title.$sql."\r\n", FILE_APPEND);
    }
}
